<template>
  <div>
    <!-- 搜索部分 开始 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="客户姓名">
        <el-input
          v-model="searchForm.name"
          placeholder="请输入"
          size="small"
          @keydown.enter.native="handleSearch()"
          @keydown.esc.native="handleClearSearch()"
        ></el-input>
      </el-form-item>
      <el-form-item label="电话号码">
        <el-input
          v-model="searchForm.phone"
          placeholder="请输入"
          size="small"
          @keydown.enter.native="handleSearch()"
          @keydown.esc.native="handleClearSearch()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" size="small">
          <i class="el-icon-search"></i>
          查询
        </el-button>
        <el-button type="warning" @click="handleClearSearch" size="small">
          <i class="el-icon-search"></i>
          清除条件
        </el-button>
        <el-button type="danger" @click="handleDeleteByChosen" size="small">
          <i class="el-icon-delete-solid"></i>
          批量删除
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="
            initAddForm();
            dialogAddFormVisible = true;
          "
          size="small"
        >
          <i class="el-icon-plus"></i>
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 搜索部分结束 -->

    <!-- 表格部分 开始-->

    <el-table
      :data="tableList"
      style="width: 100%"
      height="70vh"
      header-cell-class-name="tableHeaderCell"
      border
      v-loading="loadingTable"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="ID" sortable width="80">
      </el-table-column>
      <el-table-column prop="name" label="客户姓名" sortable width="120">
      </el-table-column>
      <el-table-column
        prop="gender"
        scope="row"
        label="性别"
        sortable
        width="80"
      >
        <template slot-scope="scope">
          {{ scope.row.gender }}
        </template>
      </el-table-column>
      <el-table-column prop="addr" label="地址" sortable width="300">
      </el-table-column>
      <el-table-column prop="phone" label="电话号码" sortable width="150">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleOpenEditDialog(scope.row)"
          >
            <i class="el-icon-edit-outline"></i>
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="removeCustomerById(scope.row)"
          >
            <i class="el-icon-delete"></i>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格部分 结束-->

    <!-- 分页开始 -->
    <div class="page-container">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="[5, 10, 30, 50]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination>
    </div>
    <!-- 分页结束 -->

    <!-- 添加客户的对话框-->
    <el-dialog
      title="添加新客户"
      :visible.sync="dialogAddFormVisible"
      width="30%"
      :before-close="beforeCloseDialog"
    >
      <el-form :model="addForm" :rules="addFormRule" ref="addForm">
        <el-form-item label="姓名" prop="name" label-width="120">
          <el-input v-model="addForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone" label-width="120">
          <el-input v-model="addForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="addr" label-width="120">
          <el-input v-model="addForm.addr" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" label-width="120">
          <el-radio-group v-model="addForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAddFormVisible = false" size="small"
          >取 消</el-button
        >
        <el-button
          type="primary"
          :disabled="disabledAddOkBtn"
          :loading="loadingAddOkBtn"
          @click="handleAddDriver(addForm)"
          size="small"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑客户的对话框-->
    <el-dialog
      title="编辑客户信息"
      :visible.sync="dialogEditFormVisible"
      width="30%"
      :before-close="beforeCloseDialog"
    >
      <el-form :model="editForm" :rules="editFormRule" ref="editForm">
        <el-form-item label="姓名" prop="name" label-width="120">
          <el-input
            v-model="editForm.name"
            autocomplete="off"
            @keydown.enter.native="handleUpdateCustomer(editForm)"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone" label-width="120">
          <el-input
            v-model="editForm.phone"
            autocomplete="off"
            @keydown.enter.native="handleUpdateCustomer(editForm)"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="addr" label-width="120">
          <el-input
            v-model="editForm.addr"
            autocomplete="off"
            @keydown.enter.native="handleUpdateCustomer(editForm)"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender" label-width="120">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false" size="small"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="handleUpdateCustomer(editForm)"
          size="small"
          :disabled="disabledEditOkBtn"
          :loading="loadingEditOkBtn"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import customerApi from "@/api/customer.js";
export default {
  name: "Customer",
  data() {
    return {
      loadingAddOkBtn: false, // 添加弹窗确认按钮是否进行加载
      disabledAddOkBtn: false, // 添加弹窗确认按钮是否禁用
      loadingEditOkBtn: false, // 编辑弹窗确认按钮是否进行加载
      disabledEditOkBtn: false, // 编辑弹窗确认按钮是否禁用
      loadingTable: false, // 加载表格
      dialogAddFormVisible: false, // 添加的对话框是否可见
      dialogEditFormVisible: false,
      breadcrumbRoutes: [], // 面包屑路由
      searchForm: {
        // 查询表单
        id: "", // 名字
        addr: "", // 客户地址
        name: "", // 名称
        phone: "",
      },
      editForm: {
        // 编辑师傅的表单信息
        id: null,
        name: "",
        phone: "",
        addr: "",
        gender: 1,
      },
      addForm: {
        // 添加师傅的表单信息
        name: "",
        phone: "",
        addr: "",
        gender: "MAN",
      },
      addFormRule: {
        name: [{ required: true, message: "名字不能为空", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/, //正则校验不用字符串
            message: "请填写正确的联系电话",
            trigger: "blur",
          },
        ],
        addr: [{ required: true, message: "地址不能为空", trigger: "blur" }],
        // gender: [
        //     { required: true, message: '性别不能为空', trigger: 'blur' }
        // ]
      },
      editFormRule: {
        name: [{ required: true, message: "名字不能为空", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/, //正则校验不用字符串
            message: "请填写正确的联系电话",
            trigger: "blur",
          },
        ],
        addr: [{ required: true, message: "地址不能为空", trigger: "blur" }],
        // gender: [
        //     { required: true, message: '性别不能为空', trigger: 'blur' }
        // ]
      },
      ////////////////////////////////////////////////////////////////////////////////////////   需要向后台请求获取的数据

      tableList: [], // 表格数据
      ////////////////////////////////////////////////////////////////////////////////////////  需要向后台请求获取的数据
      chosenTableList: [], // 选择的表格数据
      pageInfo: {
        pageNum: 1, // 当前页
        pageSize: 5, // 每一页的记录数量
        total: 20, // 总的记录数
      },
    };
  },
  created() {
    // 加载面包屑
    this.$bus.$emit("loadBreadcrumb", null);
    // 更新分页信息
    this.pageInfo.pageNum = Number(this.$route.params.pageNum) || 1;
    this.pageInfo.pageSize = Number(this.$route.params.pageSize) || 5;
    this.searchForm.pageNum = this.pageInfo.pageNum;
    this.searchForm.pageSize = this.pageInfo.pageSize;
    // 获取客户数据
    this.getTableList();
  },
  mounted() {},
  computed: {
    routePageNum() {
      return this.$route.query.pageNum;
    },
    routePageSize() {
      return this.$route.query.pageSize;
    },
  },
  methods: {
    beforeCloseDialog(done) {
      this.$confirm(`是否确认取消操作?`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        done();
      });
    },
    // 当点击搜索按钮
    handleSearch() {
      this.$router.push({
        path: this.$route.path,
        query: {
          pageNum: this.$route.pageNum,
          pageSize: this.$route.pageSize,
        },
      });
      this.getTableList(this.routePageNum, this.routePageSize);
    },
    // 清除筛选条件的查询
    handleClearSearch() {
      this.searchForm.id = "";
      this.searchForm.addr = "";
      this.searchForm.name = "";
      this.searchForm.phone = "";
      this.handleSearch();
    },
    // 当选择表格某一项时
    handleSelectionChange(dataList) {
      this.chosenTableList = dataList;
    },
    // 切换页面时
    handleCurrentChange(pageNum) {
      this.$router.push({
        path: this.$route.path,
        query: {
          pageNum: pageNum,
          pageSize: this.$route.query.pageSize,
        },
      });
      this.getTableList(pageNum, this.routePageSize);
    },
    // 修改每一页记录显示数量时
    handlePageSizeChange(pageSize) {
      this.$router.push({
        path: this.$route.path,
        query: {
          pageNum: this.$route.query.pageNum,
          pageSize: pageSize,
        },
      });
      this.getTableList(1, pageSize);
    },

    // 根据师傅的 id 修改状态
    updateStatusById(customer) {
      this.$message.success(`师傅修改状态信息后:${JSON.stringify(customer)}`);
    },

    handleDeleteByChosen() {
      // 如果没有选择客户, 则弹出提示并返回
      if (this.chosenTableList.length == 0) {
        return this.$message.warning("请先选择需要删除的客户");
      }
      // 提取出每个客户的ID
      const customerIds = [];
      this.chosenTableList.forEach((customer) => customerIds.push(customer.id));

      this.$confirm(
        `是否确认删除id为[${customerIds}]的这些客户？`,
        "温馨提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        customerApi.deleteCustomerByIds(customerIds).then(() => {
          this.$message.success("删除成功!");
          setTimeout(() => {
            this.getTableList(1, this.routePageSize);
          }, 1000);
        });
      });
    },
    // 添加新客户
    handleAddDriver(customer) {
      // 禁用 按钮
      this.disabledAddOkBtn = true;
      // 加载按钮
      this.loadingAddOkBtn = true;
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          customerApi.addCustomer(customer).then(() => {
            this.$message.success("添加成功!");

            setTimeout(() => {
              this.getTableList(this.routePageNum, this.routePageSize);
              // 取消加载
              this.loadingAddOkBtn = false;
            }, 1000);

            // 关闭窗口
            this.dialogAddFormVisible = false;
          });
        } else {
          return false;
        }
      });
      // 取消禁用 按钮
      this.disabledAddOkBtn = false;
      // 取消加载
      this.loadingAddOkBtn = false;
    },
    // 打开编辑客户的弹窗
    handleOpenEditDialog(customer) {
      this.editForm.name = customer.name;
      this.editForm.id = customer.id;
      this.editForm.phone = customer.phone;
      this.editForm.gender = customer.gender;
      this.editForm.addr = customer.addr;
      this.dialogEditFormVisible = true;
    },
    // 初始化表单信息
    initAddForm() {
      this.addForm.name = "";
      this.addForm.phone = "";
      this.addForm.addr = "";
      this.addForm.gender = "男";
    },
    // 更新客户信息
    handleUpdateCustomer(customer) {
      // 禁用 按钮
      this.disabledEditOkBtn = true;
      // 加载按钮
      this.loadingEditOkBtn = true;
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          customerApi.updateCustomerById(customer).then(() => {
            this.$message.success("修改成功!");
            setTimeout(() => {
              this.dialogEditFormVisible = false;
              this.getTableList(this.routePageNum, this.routePageSize);
            }, 1000);
          });
        } else {
          return false;
        }
      });
      setTimeout(() => {
        this.loadingEditOkBtn = false;
        this.disabledEditOkBtn = false;
      }, 1200);
    },
    // 根据客户ID删除信息
    removeCustomerById(customer) {
      this.$confirm(`是否确认删除客户[${customer.name}]？`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        customerApi.deleteCustomerByIds([customer.id]).then(() => {
          this.$message.success("删除成功!");
          setTimeout(() => {
            this.getTableList(1, this.routePageSize);
          }, 1000);
        });
      });
    },
    ////////////////////////////////// 请求数据 的方法 ///////////////////////////////
    getTableList(pageNum = 1, pageSize = 5) {
      this.loadingTable = true;
      customerApi
        .getPage({ ...this.searchForm, pageNum, pageSize })
        .then((response) => {
          const { pageInfo } = response.data;
          // 记录表格数据
          console.log("111:" + JSON.stringify(pageInfo.customerList));
          this.tableList = pageInfo.customerList;
          // 记录分页数据
          this.pageInfo.pageNum = pageInfo.pageNum;
          this.pageInfo.pageSize = pageInfo.pageSize;
          this.pageInfo.total = pageInfo.total;
          setTimeout(() => {
            this.loadingTable = false;
          }, 300);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.page-container {
  margin-top: 20px;
  text-align: center;
}
:deep .tableHeaderCell{
    background: #99bda7 !important;
    color: #2e7565;
}
</style>